package com.registration.web.utils.jackson;

import org.codehaus.jackson.Base64Variants;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;
import org.codehaus.jackson.map.TypeDeserializer;
import org.codehaus.jackson.map.deser.StdDeserializer;

import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: lruiz
 * Date: 5/25/11
 * Time: 10:36 PM
 * To change this template use File | Settings | File Templates.
 */
public class StringTrimmerDeserializer extends JsonDeserializer<String> {

    @Override
    public String deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        JsonToken curr = jp.getCurrentToken();
        // Usually should just get string value:
        if (curr == JsonToken.VALUE_STRING) {
            return trimToNull(jp.getText());
        }
        // [JACKSON-330]: need to gracefully handle byte[] data, as base64
        if (curr == JsonToken.VALUE_EMBEDDED_OBJECT) {
            Object ob = jp.getEmbeddedObject();
            if (ob == null) {
                return null;
            }
            if (ob instanceof byte[]) {
                return Base64Variants.getDefaultVariant().encode((byte[]) ob, false);
            }
            // otherwise, try conversion using toString()...
            return trimToNull(ob.toString());
        }
        // Can deserialize any scalar value, but not markers
        if (curr.isScalarValue()) {
            return trimToNull(jp.getText());
        }
        throw ctxt.mappingException(String.class);
    }

    public String trimToNull(String v) {
        return v == null || v.trim().isEmpty() ? null : v.trim();
    }
}
